import log from "./logger";
import {nconf, axios} from "../node-test";
import {Settings, vlpr} from "./interfaces";
import {writeFile, readFileSync} from "fs";

class SettingsImpl implements Settings {
    public name: string;
    public productKey: string
    public deviceName: string
    public deviceSecret: string
    public url: string
    public equipmentType: string
    public comPath: string
    public combaudRate: number
    public dvr: vlpr[]
    public vehicleEnter: boolean
    public notZeroPlate: boolean
    public barrierGate: 'no' | 'out' | 'inout'
    public platformId: number
    public platformName: string
    public led1 = ""
    public led2 = ""
    public weightWenTimeout = 4
    public readyPlateNum = 3
    public isSayWeight = false
    public gatewayEnable = false
    public asyncWeight = false
    // 忽略红外
    public ignore = false;
    // 是否根据红外判断是否结束上一辆车过磅流程
    public active2ReadyState = false;
    public printerIp = '';
    public qrInComPath = '';
    public qrOutComPath = '';
    public saleBtnWeighing = false;
    public vmUrl = '';
    // public aliIotDisable = false;
    public weightAddress = '127.0.0.1:39999'
    public printerSocketDestroy = false;
    public weighType: 'SM,TM,DD';
    // 控制器常开，默认是常闭
    public normalOpen = false;
    public mqttServer = '';
    public lokiHost = '';

    writeConfig(d: any) {
        // 保存配置文件
        writeFile('config.json', JSON.stringify(d, null, 4), 'utf-8', (err: any) => {
            if (err) {
                log.error('writeFile error: ', err);
            } else {
                log.info("写入文件配置成功")
            }
        });
    }

    readConfig() {
        // 读取配置文件
        log.info("访问网络失败，读取本地配置");
        // const {readFileSync} = require('fs');
        const data = readFileSync('config.json');
        const d = JSON.parse(data.toString());
        log.info(d);
        this.loadConfig(d);
    }

    loadConfig(d: any) {
        this.name = d.name;
        this.productKey = d.productKey
        this.deviceSecret = d.deviceSecret
        this.url = d.url
        this.comPath = d.comPath
        this.combaudRate = d.combaudRate
        this.equipmentType = d.equipmentType
        this.dvr = d.dvr
        this.vehicleEnter = d.vehicleEnter
        this.notZeroPlate = d.notZeroPlate
        this.barrierGate = d.barrierGate
        this.platformId = d.platformId
        this.platformName = d.platformName
        this.led1 = d.extSettings.led1 || ''
        this.led2 = d.extSettings.led2 || ''
        this.weightWenTimeout = d.extSettings.weightWenTimeout || 4
        this.readyPlateNum = d.extSettings.readyPlateNum || 3
        this.isSayWeight = d.extSettings.isSayWeight || false
        this.gatewayEnable = d.extSettings.gatewayEnable || false
        this.asyncWeight = d.extSettings.asyncWeight || false
        this.ignore = d.extSettings.ignore || false
        this.active2ReadyState = d.extSettings.active2ReadyState || false
        this.printerIp = d.extSettings.printerIp || ''
        this.qrInComPath = d.extSettings.qrInComPath || ''
        this.qrOutComPath = d.extSettings.qrOutComPath || ''
        this.saleBtnWeighing = d.extSettings.saleBtnWeighing || false
        this.vmUrl = d.extSettings.vmUrl
        // this.aliIotDisable = d.extSettings.aliIotDisable || false
        this.weightAddress = d.extSettings.weightAddress || '127.0.0.1:39999'
        this.printerSocketDestroy = d.extSettings.printerSocketDestroy || false
        this.weighType = d.extSettings.weighType || 'SM,TM,DD'
        this.normalOpen = d.extSettings.normalOpen || false
        this.mqttServer = d.extSettings.mqttServer || "mq.wechain360.com"
        this.lokiHost = d.extSettings.lokiHost;
    }

    getConfig(settingsUrl: string) {
        log.info('getConfig()')
        return new Promise((resolve, reject) => {
            axios.request({
                method: "GET",
                url: `${settingsUrl}${this.deviceName}`,
            }).then((response) => {
                if (response.status === 200 && response.data.id) {
                    const d = response.data;
                    log.info("settings:", d);
                    this.loadConfig(d);
                    this.writeConfig(d);
                    resolve("ok");
                } else {
                    log.error("获取配置返回不是200？")
                    this.readConfig();
                }
            }).catch((error) => {
                log.error("获取配置网络错误")
                this.readConfig();
            });
        })
    }

    async init() {
        nconf.argv().env();
        this.deviceName = nconf.get('deviceName');
        const settingsUrl = nconf.get('settingsUrl')
        if (!this.deviceName) {
            throw new Error("deviceName error")
        }
        await this.getConfig(settingsUrl);
    }
}

const settings = new SettingsImpl();

export default settings;